﻿Imports System.IO
Imports System.Text.RegularExpressions

Public Class Form2

    Private Sub Form2_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'check each address for validity;
        'must start with a 1 or a 3; 1==Production, 3==Test
        'must be 27-34 alpha numeric characters;
        '^(1|3)[a-zA-Z0-9]{26,33}$
        Dim MyAddresses As String = String.Empty
        For Each Address As String In txtAddresses.Text.Split(vbCrLf)
            If (Address.Trim.Length > 0) Then
                If Regex.IsMatch(Address.Trim, "^(1|3)[a-zA-Z0-9]{26,33}$", RegexOptions.IgnoreCase) Then
                    MyAddresses &= Address & "|"
                Else
                    MsgBox(String.Format("The address:{1}{2}{0}{2}{1}does not appear to be valid.{1}Please remove it or fix it", Address, vbCrLf, ControlChars.Quote), MsgBoxStyle.Exclamation, "Invalid Address")
                    e.Cancel = True
                    Exit Sub
                End If
            End If
        Next

        MyAddresses = MyAddresses.Replace(vbCrLf, String.Empty)
        MyAddresses = MyAddresses.Replace(vbCr, String.Empty)
        MyAddresses = MyAddresses.Replace(vbLf, String.Empty)
        File.WriteAllText(Form1.File_AddressDat, MyAddresses)
        Form1.Addresses = MyAddresses.TrimEnd("|")

    End Sub

    Private Sub Form2_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        txtAddresses.Text = String.Empty
        Form1.LoadAddresses()
    End Sub

    Private Sub txtAddresses_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class